﻿<%@ WebHandler Language="C#" Class="ContainerStepInfoCheckHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using BusinessRule.Common;
using System.Linq;
//Description: 工步检验处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:zhangrj
//create Date:2022-08-05
public class ContainerStepInfoCheckHandler : IHttpHandler, IRequiresSessionState
{

    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    uLMSWorkReportIBusiness reportBusiness = uMESBusinessFactory.instance.GetuLMSWorkReportObject();
    uLMSCheckIBusiness checkBusiness = uMESBusinessFactory.instance.GetuLMSCheckObject();
    uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    uLMSContainercurrentinfoIBusiness m_ConCurrentinfo = uMESBusinessFactory.instance.GetuLMSContainerCurrentInfoObject();
    uLMSCommissioningIBusiness m_Commission = uMESBusinessFactory.instance.GetuLMSCommissioning();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "数据过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "GetStepInfoCheckList": //获取主批次
                    GetStepInfoCheckList(context);
                    break;
                case "GetStepInfoDetailCheckList": //获取详细批次
                    GetStepInfoDetailCheckList(context);
                    break;
                case "GetStepInfoReportList": //获取工步报工详细（检验弹窗页面）
                    GetStepInfoReportList(context);
                    break;
                case "IsValidContainer": //验证批次
                    IsValidContainer(context);
                    break;
                case "SetInputCheckPoint": //设置检测项
                    SetInputCheckPoint(context);
                    break;
                case "SaveStepInfoCheckInfo": //保存工步检验数据
                    SaveStepInfoCheckInfo(context);
                    break;
                case "GetStepInfoDeletableCheckInfo": //获取可撤销的工步检验数据
                    GetStepInfoDeletableCheckInfo(context);
                    break;
                case "SaveStepInfoCheckCancel": //保存撤销的工步检验数据
                    SaveStepInfoCheckCancel(context);
                    break;
                case "GetStepInfoBatchCheckList": //获取批量工步检验数据
                    GetStepInfoBatchCheckList(context);
                    break;
                case "SaveStepInfoBatchCheckData": //保存批量工步检验数据
                    SaveStepInfoBatchCheckData(context);
                    break;
                case "SetDelegateLHSession": //设置理化试验的批次数据
                    SetDelegateLHSession(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    /// <summary>
    /// 设置理化试验的批次数据（热表）
    /// </summary>
    /// <param name="context"></param>
    public void SetDelegateLHSession(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string containerID = context.Request["containerID"].ToString();
        string stepInfoID = context.Request["stepInfoID"].ToString();
        string sql = string.Format(@"SELECT c.containerid,c.containername,c.productid,c.productname,c.productdescription,
                        c.workflowstepname,c.workflowstepid,c.qty wipqty,sum(nvl(csw.qty,0)) workreportnum
                        FROM containercurrentinfo c 
                        LEFT JOIN containerstepworkreport2 csw ON csw.containerid = c.containerid 
                        AND csw.workflowstepid = c.workflowstepid AND csw.stepinfoid='{1}' AND csw.isuse = 0
                        WHERE c.containerid = '{0}' AND csw.containerstepworkreportid IS NOT NULL
                        GROUP BY c.containerid,c.containername,c.productid,c.productname,c.productdescription,
                        c.workflowstepname,c.workflowstepid,c.qty", containerID, stepInfoID);
        DataTable dtContainer = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtContainer.Rows.Count == 0)
        {
            result.Result = false; result.Message = "批次无报工数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        context.Session["PopupData"] = dtContainer;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取批量检验数据（热表）
    /// </summary>
    /// <param name="context"></param>
    public void GetStepInfoBatchCheckList(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("CurrentPageIndex", context.Request["pageIndex"].ToString());
        para.Add("PageSize", context.Request["pageSize"].ToString());
        para.Add("OrderName", context.Request["orderName"].ToString());
        para.Add("ProductName", context.Request["productName"].ToString());
        para.Add("ContainerName", context.Request["containerName"].ToString());
        para.Add("CombinateName", context.Request["combinateName"].ToString());
        //string strSelectChecker = "";
        //strSelectChecker = commonBusiness.GetFatoryAttributes(m_UserInfo.FactoryID, "报工选择检验"); //获取工厂报工是否选择检验员信息
        //if (strSelectChecker == "是")
        //{
        //    para.Add("CheckerID", m_UserInfo.EmployeeID.ToString());
        //}
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        result = checkBusiness.GetRBStepInfoBatchCheckList(para);
        //加入判断是否有录入检测项
        result.DBTable.Columns.Add("IsFillCheckPoint");
        string msg = string.Empty;
        foreach (DataRow item in result.DBTable.Rows)
        {
            msg = "";
            m_ContainerObj.IsValidRBCheckPointByStepinfo(item, 1, ref msg);
            item["IsFillCheckPoint"] = msg;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存工步批量检验
    /// </summary>
    /// <param name="context"></param>
    public void SaveStepInfoBatchCheckData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dtCheck = JsonConvert.DeserializeObject<DataTable>(context.Request["paramDt"].ToString());
        if (!dtCheck.Columns.Contains("NOTES"))
        {
            dtCheck.Columns.Add("NOTES");
        }
        //
        int combinateCount = dtCheck.AsEnumerable().Where(p => string.IsNullOrWhiteSpace(p["containerid"].ToString())).Count();//合卡批次的数量
        int commCount = dtCheck.AsEnumerable().Where(p => !string.IsNullOrWhiteSpace(p["containerid"].ToString())).Count();//正常批次的数量
        if (combinateCount > 0 && commCount > 0)
        {
            result.Result = false;
            result.Message = "同时选择了合卡批次和正常批次，请重新选择";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (combinateCount > 0)
        {
            dtCheck = GetCombinateContainerDetail(dtCheck);
        }

        string msg = "";
        DataTable dtVaildCheck = dtCheck.Clone();//有效的工步检验
        DataTable dtContainer = dtCheck.DefaultView.ToTable(true, new string[4] { "ContainerID", "WorkflowstepID", "StepInfoID", "StepSeq" });
        //验证检验的工步是否有效（筛选工步是否跳顺序号报工的）
        foreach (DataRow item in dtContainer.Rows)
        {
            DataRow[] drs = dtCheck.Select("containerid='" + item["ContainerID"].ToString() + "' and workflowstepid='" + item["WorkflowstepID"].ToString() + "' and stepInfoID='" + item["StepInfoID"].ToString() + "'");
            //验证是否录入检测项
            if (!m_ContainerObj.IsValidRBCheckPointByStepinfo(item, 1, ref msg))
            {
                result.Result = false;
                result.Message = "存在未录入检测项的工步";
                break;
            }
            if (checkBusiness.IsValidBatchStepInfoCheck(item))
            {
                foreach (DataRow dr1 in drs)
                {
                    dtVaildCheck.Rows.Add(dr1.ItemArray);
                }
            }
        }
        if (!result.Result)
        {
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //填充检验数据
        if (dtVaildCheck.Rows.Count == 0)
        {
            result.Result = false;
            result.Message = "存在顺序号低的工步未报工完";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        ServerHostInfo host = new ServerHostInfo();
        host.UserName = m_UserInfo.APIUserName;
        host.Password = m_UserInfo.APIPassword;
        DataTable levelAttributes = commonBusiness.GetFatoryAttributes(m_UserInfo.FactoryID);
        List<ContainerCheckInfoDTO> checkList = new List<ContainerCheckInfoDTO>();
        List<Dictionary<string, object>> paras = new List<Dictionary<string, object>>();
        //List<string> repairContianer = new List<string>();//储存返件报工的批次
        //List<string> testContianer = new List<string>();//储存试件报工的批次
        string StepWorkReportIDList = "";//报工ID列表串
        foreach (DataRow dr in dtVaildCheck.Rows)
        {
            msg = "";
            if (commonBusiness.JudeContainerHold(dr["ContainerID"].ToString(), ref msg))
            {
                result.Result = false;
                result.Message = "批次" + dr["ContainerID"].ToString() + "已暂停,暂停原因：" + msg;
                break;
            }
            if (string.IsNullOrWhiteSpace(dr["ContainerStepWorkReportID"].ToString()))
            {
                result.Result = false;
                result.Message = "没有报工数据";
                break;
            }
            if (string.IsNullOrWhiteSpace(dr["EmployeeName"].ToString()))//报工人为空
            {
                Dictionary<string, object> updatePara = new Dictionary<string, object>();
                updatePara["FactoryID"] = m_UserInfo.FactoryID;
                updatePara["WorkerID"] = m_UserInfo.EmployeeID;
                updatePara["ContainerStepWorkReportID"] = dr["ContainerStepWorkReportID"].ToString();
                paras.Add(updatePara);
            }
            ContainerCheckInfoDTO checkDto = new ContainerCheckInfoDTO();
            checkDto.DefectQty = 0;//超差数
            checkDto.ReworkQty = 0;//返修数
            checkDto.LossQty = 0;//报废数
            checkDto.CheckQty = int.Parse(dr["QTY"].ToString());//检验数量(等于报工数)
            checkDto.WIPQty = int.Parse(dr["WIPQTY"].ToString());//在制数
            checkDto.SpecimenLossQty = 0;//需开废票试件数
            checkDto.AcceptanceQty = checkDto.CheckQty - checkDto.LossQty - checkDto.SpecimenLossQty;//合格数量
            checkDto.AcceptanceQty2 = checkDto.AcceptanceQty - checkDto.DefectQty - checkDto.ReworkQty;
            checkDto.ContainerID = dr["ContainerID"].ToString();//批次ID
            checkDto.ContainerName = dr["ContainerName"].ToString();//批次名
            checkDto.WorkflowstepID = dr["WorkflowstepID"].ToString();//工序ID
            checkDto.StepInfoID = dr["StepInfoID"].ToString();//工步ID
            checkDto.ContainerStepWorkReportID = dr["ContainerStepWorkReportID"].ToString();//报工ID
            checkDto.FactoryID = m_UserInfo.FactoryID;//工厂ID
            checkDto.CheckerID = m_UserInfo.EmployeeID.ToString();//检验员
            checkDto.CheckNote = dr["NOTES"].ToString();//检验备注
            checkDto.FirstCheckContainerNo = "";//首检批次号
            checkDto.FirstCheckBillNo = GetFirstCheckBillNo();

            checkDto.ReportType = int.Parse(dr["CheckType"].ToString());//报工类型
            //if (checkDto.ReportType == 4)//返件报工
            //{
            //    repairContianer.Add(dr["ContainerID"].ToString());
            //}
            //if (checkDto.ReportType == 3)//试件报工
            //{
            //    testContianer.Add(dr["ContainerID"].ToString());
            //}
            StepWorkReportIDList += checkDto.ContainerStepWorkReportID + ",";
            checkList.Add(checkDto);
        }
        //验证是否已存在检验（此情况针对在两台终端机同时登录同时检）
        if (result.Result && !string.IsNullOrWhiteSpace(StepWorkReportIDList))
        {
            StepWorkReportIDList = StepWorkReportIDList.Trim(',');
            DataTable dtCheck1 = checkBusiness.ContainerCheck2ValidateList(StepWorkReportIDList, 0);
            if (dtCheck1.Rows.Count > 0)
            {
                result.Result = false;
                result.Message = "存在已有检验记录的工步，请重新查询";
            }
            if (!checkBusiness.IsVaildWorkReportForStepInfoCheck(StepWorkReportIDList, 0))
            {
                result.Result = false;
                result.Message = "存在工步已撤销，请刷新页面";
            }
        }
        if (result.Result)
        {
            //保存检验记录
            result = checkBusiness.SaveStepInfoCheckInfo(checkList, paras);
            //检验结束，移动工序
            if (result.Result)
            {
                DataTable dtReCheck = dtCheck.DefaultView.ToTable(true, new string[6] { "ContainerID", "ContainerName", "WorkflowStepId", "workflowId", "sequence", "factoryId" });
                foreach (DataRow item in dtReCheck.Rows)
                {
                    DataTable containerQty = checkBusiness.GetAllAccepQtyListByStepInfo(item["ContainerID"].ToString());
                    int wipQty = 0, accepttanceQty = 0, lossQty = 0, defectqty = 0, reworkqty = 0;//在制数，合格数（不能用工序合格数），报废数
                    if (!string.IsNullOrWhiteSpace(containerQty.Rows[0]["QTY"].ToString()))
                    {
                        wipQty = int.Parse(containerQty.Rows[0]["QTY"].ToString());
                    }
                    //检查总表stepcheckNum,firstCheckNum
                    //string strUpdateinfo = "";
                    //strUpdateinfo = m_ConCurrentinfo.UpdateContainerCurrentinfoCheckInfo2(item["ContainerID"].ToString(), item["WorkflowStepID"].ToString());
                    BusinessRule.Common.LogHelp.WriteOrcale("检验日志记录" + "@^" + "批次：" + item["ContainerID"].ToString() + "@^" + "工序：" + item["WorkflowStepID"].ToString() + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_UserInfo.FullName); //写入数据库   
                    DataTable dtaccqty = checkBusiness.GetStepInfoAccepQty(item);//查询工序下的所有工步检验数
                    DataRow[] dacs = dtaccqty.Select("checkqty<'" + wipQty + "'");
                    //只要有工步的检验数小于在制数，则不移动
                    if (dacs.Length > 0)
                    {
                        continue;
                    }
                    lossQty = int.Parse(dtaccqty.Compute("SUM(LOSSQTY)", string.Empty).ToString());//工序下所有工步报废数总和
                    defectqty = int.Parse(dtaccqty.Compute("SUM(defectqty)", string.Empty).ToString());//工序下所有工步超差数总和
                    reworkqty = int.Parse(dtaccqty.Compute("SUM(reworkqty)", string.Empty).ToString());//工序下所有工步返修数总和
                    accepttanceQty = int.Parse(dtaccqty.Compute("Min(Acceptanceqty)", "true").ToString());//最小的合格数
                    if (accepttanceQty == 0)//合格总数为0
                    {
                        continue;
                    }
                    FillStepCheckInfo(item, accepttanceQty, lossQty, defectqty, reworkqty);//所有工步干完，填充工序检验信息
                    //工序移动
                    msg = "";
                    result.Result = checkBusiness.MoveNextStep(new Dictionary<String, String>() {{"ContainerID", item["ContainerID"].ToString()},
                                                                                    {"WorkflowStepID", item["WorkFlowStepID"].ToString()},
                                                                                     {"WorkflowID", item["WorkflowID"].ToString()},
                                                                                    {"Sequence", item["Sequence"].ToString()},
                                                                                    {"ContainerName", item["ContainerName"].ToString()}
                                                                                   }, host, accepttanceQty, levelAttributes, m_UserInfo, ref msg);
                    if (!result.Result)
                    {
                        result.Message = "工序移动失败：" + msg;
                        break;
                    }
                    //if (!MoveNextStep(item, ref msg, accepttanceQty))
                    //{
                    //    result.Result = false;
                    //    result.Message = "工序移动失败：" + msg;
                    //    break;
                    //}
                }
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取可撤销的工步检验数据
    /// </summary>
    /// <param name="context"></param>
    public void GetStepInfoDeletableCheckInfo(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("CheckerID", m_UserInfo.EmployeeID.ToString());
        para.Add("ScanContainerName", context.Request["scanContainer"].ToString());
        if (!string.IsNullOrWhiteSpace(para["ScanContainerName"].ToString()))
        {
            para["ScanContainerName"] = commonBusiness.ContainerScan(para["ScanContainerName"].ToString());
        }
        uMESProcessResult result = new uMESProcessResult();
        result = checkBusiness.GetStepInfoDeletableCheckInfo(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存撤销的工步检验
    /// </summary>
    /// <param name="context"></param>
    public void SaveStepInfoCheckCancel(HttpContext context)
    {
        LogHelp.SetConfig();
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dtMain = JsonConvert.DeserializeObject<DataTable>(context.Request["paramDt"].ToString());//选中的批次
        DataTable dt = dtMain.DefaultView.ToTable(true, "stepinfoid");
        if (dt.Rows.Count > 1)
        {
            result.Result = false;
            result.Message = "请选择同一个工步撤销";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        result = checkBusiness.SaveStepInfoCheckCancel(dtMain);
        if (result.Result)
        {
            string containercheckinfoIDs = "";
            foreach (DataRow item in dtMain.Rows)
            {
                containercheckinfoIDs += string.Format("{0},", item["ContainerCheckInfoId"].ToString());
            }
            containercheckinfoIDs = containercheckinfoIDs.TrimEnd(',');
            LogHelp.WriteOrcale(String.Format("检验撤销--工步@^批次：{0}报工撤销成功@^工序:{1}工步ID:{2}检验ID:{3}@^{4}@^{5}", dtMain.Rows[0]["ContainerID"].ToString(), dtMain.Rows[0]["workflowstepID"].ToString(), dtMain.Rows[0]["StepInfoID"].ToString(), containercheckinfoIDs, Convert.ToString(Guid.NewGuid()), m_UserInfo.FullName)); //写入数据库 
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取工步检验列表
    /// </summary>
    /// <param name="context"></param>
    public void GetStepInfoCheckList(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("CurrentPageIndex", context.Request["pageIndex"].ToString());
        para.Add("PageSize", context.Request["pageSize"].ToString());
        para.Add("ScanContainerName", context.Request["scanContainer"].ToString());
        if (!string.IsNullOrWhiteSpace(para["ScanContainerName"].ToString()))
        {
            para["ScanContainerName"] = commonBusiness.ContainerScan(para["ScanContainerName"].ToString());
        }
        para.Add("ScanOrderName", context.Request["scanOrder"].ToString());
        para.Add("ProductName", context.Request["productName"].ToString());
        para.Add("ContainerName", context.Request["containerName"].ToString());
        para.Add("StepName", context.Request["stepName"].ToString());
        para.Add("CombinateName", context.Request["combinateName"].ToString());
        string strSelectChecker = "";
        strSelectChecker = commonBusiness.GetFatoryAttributes(m_UserInfo.FactoryID, "报工选择检验"); //获取工厂报工是否选择检验员信息
        if (strSelectChecker == "是")
        {
            para.Add("CheckerID", m_UserInfo.EmployeeID.ToString());
        }
        uMESProcessResult result = new uMESProcessResult();
        result = checkBusiness.GetRBContainerStepInfoCheckData(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取工步检验详细批次
    /// </summary>
    /// <param name="context"></param>
    public void GetStepInfoDetailCheckList(HttpContext context)
    {
        DataTable dtMain = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());//选中的批次
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("StepinfoId", dtMain.Rows[0]["StepinfoId"].ToString());
        para.Add("IsCombinate", dtMain.Rows[0]["iscombinate"].ToString());
        if (para["IsCombinate"] == "0") //如果不是合卡
        {
            para.Add("MfgOrderName", dtMain.Rows[0]["MfgOrderName"].ToString());
            para.Add("ProductId", dtMain.Rows[0]["ProductId"].ToString());
            para.Add("WorkflowId", dtMain.Rows[0]["WorkflowId"].ToString());
            para.Add("WorkflowstepId", dtMain.Rows[0]["WorkflowstepId"].ToString());
            para.Add("TogetherFlag", dtMain.Rows[0]["TogetherFlag"].ToString());
        }
        else
        {
            para.Add("ProductBatch", dtMain.Rows[0]["ProductBatch"].ToString());
        }
        string strSelectChecker = "";
        strSelectChecker = commonBusiness.GetFatoryAttributes(m_UserInfo.FactoryID, "报工选择检验"); //获取工厂报工是否选择检验员信息
        if (strSelectChecker == "是")
        {
            para.Add("CheckerID", m_UserInfo.EmployeeID.ToString());
        }
        DataTable dtDetail = checkBusiness.GetRBContainerStepInfoCheckDetail(para);
        //加入判断是否有录入检测项
        dtDetail.Columns.Add("IsFillCheckPoint");
        string msg = string.Empty;
        foreach (DataRow item in dtDetail.Rows)
        {
            msg = "";
            m_ContainerObj.IsValidRBCheckPointByStepinfo(item, 1, ref msg);
            item["IsFillCheckPoint"] = msg;
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, DBTable = dtDetail }));
    }
    /// <summary>
    /// 验证批次是否可以检验
    /// </summary>
    /// <param name="context"></param>
    public void IsValidContainer(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dtMain = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());//选中的批次
        string msg = "";
        string reportIds = "";
        if (commonBusiness.JudeContainerHold(dtMain.Rows[0]["ContainerId"].ToString(), ref msg))
        {
            result.Message = "该批次已暂停，暂停原因：" + msg;
            result.Result = false;
            goto L1;
        }
        if (checkBusiness.IsExistNoCheckedPreStepInfo(dtMain.Rows[0]))
        {
            result.Message = "存在未检验完的顺序号更小的工步";
            result.Result = false;
            goto L1;
        }
        foreach (DataRow item in dtMain.Rows)
        {
            if (!m_ContainerObj.IsValidRBCheckPointByStepinfo(item, 1, ref msg))
            {
                result.Message = "未录入实测值";
                result.Result = false;
                break;
            }
            reportIds += "'" + item["containerstepworkreportid"].ToString() + "',";
        }
        reportIds = result.Result ? reportIds.TrimEnd(',') : "";
        result.ReturnData = reportIds;
    L1: context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取工步报工详细（检验弹窗页面）
    /// </summary>
    /// <param name="context"></param>
    public void GetStepInfoReportList(HttpContext context)
    {
        DataSet ds = new DataSet();
        string reportIds = context.Request["params"].ToString();
        DataTable dtDetail = checkBusiness.GetStepInfoReportList(reportIds);
        dtDetail.TableName = "dtDetail";
        ds.Tables.Add(dtDetail);
        DataTable dtLossReason = commonBusiness.GetLossReasonByGroupName("报废原因组");
        dtLossReason.TableName = "dtLossReason";
        ds.Tables.Add(dtLossReason);
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, DBDataSet = ds }));
    }
    /// <summary>
    /// 设置实测值录入
    /// </summary>
    /// <param name="context"></param>
    public void SetInputCheckPoint(HttpContext context)
    {
        DataTable dtMain = JsonConvert.DeserializeObject<DataTable>(context.Request["mainDt"].ToString());//选中的工步
        //if (dtMain.Rows[0]["ContainerType"].ToString() != "7" && dtMain.Rows.Count > 1)
        //{
        //    context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "只能选择一条数据进行实测值录入" }));
        //    return;
        //}
        if (string.IsNullOrWhiteSpace(dtMain.Rows[0]["containerid"].ToString()))//如果是批量检验的合卡批次
        {
            if (dtMain.Rows.Count > 1)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "只能选择一条数据进行实测值录入" }));
                return;
            }
            string sql = @"SELECT cci.containerid,cci.containername,cci.containertype,cci.productid,cci.workflowid,s.stepinfoid,cci.workflowstepname,cci.workflowstepid
            FROM containercombinate cb
            LEFT JOIN Containercurrentinfo cci ON cci.containerid = cb.containerid
            LEFT JOIN containerstepworkreport2 csr ON csr.containerid = cci.containerid AND csr.workflowstepid = cci.workflowstepid
            LEFT JOIN containercheckinfo2 cc ON cc.containerstepworkreportid = csr.containerstepworkreportid AND cc.isuse = 0
            LEFT JOIN stepinfo s ON s.workflowstepid = csr.workflowstepid AND s.stepinfoid = csr.stepinfoid
            LEFT JOIN employee e ON e.employeeid = csr.workerid
            WHERE csr.isuse = 0 AND cc.containercheckinfoid IS NULL
            AND cci.isinstore in (-1,0) AND cci.containerstatus=1 
            AND cb.containercombinatename = '{0}' AND csr.workflowstepid='{1}' AND s.stepinfoid = '{2}'";
            dtMain = DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(string.Format(sql, dtMain.Rows[0]["ContainerName"].ToString(), dtMain.Rows[0]["workflowstepid"].ToString(), dtMain.Rows[0]["stepinfoid"].ToString()));
        }
        bool isValid = true;
        string msg = "";
        foreach (DataRow item in dtMain.Rows)
        {
            if (commonBusiness.JudeContainerHold(item["ContainerId"].ToString(), ref msg))
            {
                msg = "该批次已暂停，暂停原因：" + msg;
                isValid = false;
                break;
            }
        }
        if (isValid)
        {
            context.Session["PopupData"] = dtMain;
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = isValid, Message = msg }));
    }
    /// <summary>
    /// 保存工步检验数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveStepInfoCheckInfo(HttpContext context)
    {
        if (!m_UserInfo.Roles.Contains("检验员"))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前登录人员非检验员，请重新登录" }));
            return;
        }
        DataTable dtContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["dtContainer"].ToString());
        DataTable dtCheck = JsonConvert.DeserializeObject<DataTable>(context.Request["dtCheck"].ToString());
        if (dtContainer.Rows.Count == 0 || dtCheck.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未选择检验工序" }));
            return;
        }
        if (!dtCheck.Columns.Contains("DEFECTQTY"))
        {
            dtCheck.Columns.Add("LOSSQTY");
            dtCheck.Columns.Add("LOSSREASON");
            dtCheck.Columns.Add("REWORKQTY");
            dtCheck.Columns.Add("DEFECTQTY");
            dtCheck.Columns.Add("CHECKNOTES");
        }
        if (dtContainer.Rows[0]["iscombinate"].ToString() == "1") //如果是合卡批次
        {
            //如果存在报废，则全部都设置相同报废数
            var drs = dtCheck.AsEnumerable().Where(p => !string.IsNullOrWhiteSpace(p["LOSSQTY"].ToString()));
            if (drs.Count() > 0)
            {
                string lossqty = drs.First()["LOSSQTY"].ToString();
                foreach (DataRow item in dtCheck.Rows)
                {
                    item["LOSSQTY"] = lossqty;//
                }
            }
        }
        ServerHostInfo host = new ServerHostInfo();
        host.UserName = m_UserInfo.APIUserName;
        host.Password = m_UserInfo.APIPassword;
        DataTable levelAttributes = commonBusiness.GetFatoryAttributes(m_UserInfo.FactoryID);
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string containerType = dtContainer.Rows[0]["CONTAINERTYPE"].ToString(), StepWorkReportIDList = "";
        List<ContainerCheckInfoDTO> checkList = new List<ContainerCheckInfoDTO>();
        List<Dictionary<string, object>> paras = new List<Dictionary<string, object>>();
        List<string> repairContianer = new List<string>();//储存返件报工的批次
        List<string> testContianer = new List<string>();//储存试件报工的批次
        List<Dictionary<string, string>> changeQtyPara = new List<Dictionary<string, string>>();//报废记录参数
        if (containerType == "3")
        {
            DataTable wp = dtCheck.DefaultView.ToTable(true, new string[9] { "ContainerID", "ContainerName", "WorkflowstepID", "StepInfoID", "ContainerStepWorkReportID", "CheckType", "WIPQTY", "Qty", "EmployeeName" });
            foreach (DataRow item in wp.Rows)
            {
                string msg = "", notes = "";
                if (!m_ContainerObj.IsValidRBCheckPointByStepinfo(item, 1, ref msg))
                {
                    result.Result = false;
                    result.Message = "批次：" + item["ContainerName"].ToString() + " 未录入实测值";
                    break;
                }
                if (commonBusiness.JudeContainerHold(item["ContainerID"].ToString(), ref msg))
                {
                    result.Result = false;
                    result.Message = "批次：" + item["ContainerName"].ToString() + "已暂停,暂停原因：" + msg;
                    break;
                }
                if (string.IsNullOrWhiteSpace(item["ContainerStepWorkReportID"].ToString()))
                {
                    result.Result = false;
                    result.Message = "没有报工数据";
                    break;
                }
                if (string.IsNullOrWhiteSpace(item["EmployeeName"].ToString()))//报工人为空
                {
                    Dictionary<string, object> updatePara = new Dictionary<string, object>();
                    updatePara["FactoryID"] = m_UserInfo.FactoryID;
                    updatePara["WorkerID"] = m_UserInfo.EmployeeID;
                    updatePara["ContainerStepWorkReportID"] = item["ContainerStepWorkReportID"].ToString();
                    paras.Add(updatePara);
                }
                ContainerCheckInfoDTO checkDto = new ContainerCheckInfoDTO();
                //查询所有子序号报工
                DataRow[] drs = dtCheck.Select(string.Format("ContainerStepWorkReportID='{0}'", item["ContainerStepWorkReportID"].ToString()));
                foreach (DataRow item1 in drs)
                {
                    int DefectQty = string.IsNullOrWhiteSpace(item1["DEFECTQTY"].ToString()) ? 0 : int.Parse(item1["DEFECTQTY"].ToString());//超差数
                    int ReworkQty = string.IsNullOrWhiteSpace(item1["REWORKQTY"].ToString()) ? 0 : int.Parse(item1["REWORKQTY"].ToString());//返修数
                    int LossQty = string.IsNullOrWhiteSpace(item1["LOSSQTY"].ToString()) ? 0 : int.Parse(item1["LOSSQTY"].ToString());//报废数
                    if (DefectQty > 1 || ReworkQty > 1 || LossQty > 1 || DefectQty < 0 || ReworkQty < 0 || LossQty < 0)
                    {
                        result.Result = false;
                        result.Message = "填写的数据不能大于1，请重新填写";
                        break;
                    }
                    if ((DefectQty + ReworkQty + LossQty) > 1)
                    {
                        result.Result = false;
                        result.Message = "报废+超差+返修不能大于1，请重新填写";
                        break;
                    }
                    checkDto.DefectQty += DefectQty;
                    checkDto.ReworkQty += ReworkQty;
                    checkDto.LossQty += LossQty;
                    notes += string.IsNullOrWhiteSpace(item1["CHECKNOTES"].ToString()) ? "" : item1["CHECKNOTES"].ToString() + ",";//备注、
                    if (LossQty > 0) //如果该子序号报废，记录到报废记录表
                    {
                        Dictionary<string, string> changeDic = new Dictionary<string, string>();
                        changeDic.Add("containerCheckInfoID", checkDto.ContainerCheckInfoID);//检验ID
                        changeDic.Add("containerID", item1["ChildContainerID"].ToString());//子序号批次ID
                        changeDic.Add("changeQtyType", "2");//数量变更类型（2为报废）
                        changeDic.Add("qty", (-LossQty).ToString());//变更数量
                        changeDic.Add("reasonID", item1["LOSSREASON"].ToString());
                        changeDic.Add("scrapSourceType", "1");//数据来源类型(1为工序检验)
                        changeDic.Add("containerStepWorkReportID", item1["ContainerStepWorkReportID"].ToString());//报工ID
                        changeDic.Add("EmployeeID", m_UserInfo.EmployeeID.ToString());//记录人
                        changeDic.Add("WorkflowstepID", item["WorkflowstepID"].ToString());//工序ID
                        changeDic.Add("StepInfoID", item["StepInfoID"].ToString());//工步ID
                        changeQtyPara.Add(changeDic);
                    }
                }
                checkDto.CheckQty = int.Parse(item["QTY"].ToString());//检验数量(等于报工数)
                if (checkDto.CheckQty < (checkDto.DefectQty + checkDto.ReworkQty + checkDto.LossQty))
                {
                    result.Result = false;
                    result.Message = "填写数量大于总检测的数量，请重新填写";
                    break;
                }
                checkDto.WIPQty = int.Parse(item["WIPQTY"].ToString());//在制数
                // checkDto.SpecimenLossQty = string.IsNullOrWhiteSpace(item["SPECIMENLOSSQTY"].ToString()) ? 0 : int.Parse(item["SPECIMENLOSSQTY"].ToString());//需开废票试件数
                checkDto.AcceptanceQty = checkDto.CheckQty - checkDto.LossQty;//合格数量
                checkDto.AcceptanceQty2 = checkDto.AcceptanceQty - checkDto.DefectQty - checkDto.ReworkQty;
                checkDto.ContainerID = item["ContainerID"].ToString();//批次ID
                checkDto.ContainerName = item["ContainerName"].ToString();//批次名
                checkDto.WorkflowstepID = item["WorkflowstepID"].ToString();//工序ID
                checkDto.StepInfoID = item["StepInfoID"].ToString();//工步ID
                checkDto.ContainerStepWorkReportID = item["ContainerStepWorkReportID"].ToString();//报工ID
                checkDto.FactoryID = m_UserInfo.FactoryID;//工厂ID
                checkDto.CheckerID = m_UserInfo.EmployeeID.ToString();//检验员
                checkDto.FirstCheckContainerNo = "";//首检批次号
                checkDto.FirstCheckBillNo = GetFirstCheckBillNo();
                checkDto.CheckNote = notes.Trim(',');//检验备注
                checkDto.ReportType = int.Parse(item["CheckType"].ToString());//报工类型
                if (checkDto.ReportType == 4)//返件报工
                {
                    repairContianer.Add(item["ContainerID"].ToString());
                }
                if (checkDto.ReportType == 3)//试件报工
                {
                    testContianer.Add(item["ContainerID"].ToString());
                }
                StepWorkReportIDList += checkDto.ContainerStepWorkReportID + ",";
                checkList.Add(checkDto);
            }
        }
        else
        {
            foreach (DataRow item in dtCheck.Rows)
            {
                string msg = "";
                if (!m_ContainerObj.IsValidRBCheckPointByStepinfo(item, 1, ref msg))
                {
                    result.Result = false;
                    result.Message = "批次：" + item["ContainerName"].ToString() + " 未录入实测值";
                    break;
                }
                if (commonBusiness.JudeContainerHold(item["ContainerID"].ToString(), ref msg))
                {
                    result.Result = false;
                    result.Message = "批次" + item["ContainerName"].ToString() + "已暂停,暂停原因：" + msg;
                    break;
                }
                if (string.IsNullOrWhiteSpace(item["ContainerStepWorkReportID"].ToString()))
                {
                    result.Result = false;
                    result.Message = "没有报工数据";
                    break;
                }
                if (string.IsNullOrWhiteSpace(item["EmployeeName"].ToString()))//报工人为空
                {
                    Dictionary<string, object> updatePara = new Dictionary<string, object>();
                    updatePara["FactoryID"] = m_UserInfo.FactoryID;
                    updatePara["WorkerID"] = m_UserInfo.EmployeeID;
                    updatePara["ContainerStepWorkReportID"] = item["ContainerStepWorkReportID"].ToString();
                    paras.Add(updatePara);
                }
                ContainerCheckInfoDTO checkDto = new ContainerCheckInfoDTO();
                checkDto.DefectQty = string.IsNullOrWhiteSpace(item["DEFECTQTY"].ToString()) ? 0 : int.Parse(item["DEFECTQTY"].ToString());//超差数
                checkDto.ReworkQty = string.IsNullOrWhiteSpace(item["REWORKQTY"].ToString()) ? 0 : int.Parse(item["REWORKQTY"].ToString());//返修数
                checkDto.LossQty = string.IsNullOrWhiteSpace(item["LOSSQTY"].ToString()) ? 0 : int.Parse(item["LOSSQTY"].ToString());//报废数
                checkDto.CheckQty = int.Parse(item["QTY"].ToString());//检验数量(等于报工数)
                if (checkDto.CheckQty < (checkDto.DefectQty + checkDto.ReworkQty + checkDto.LossQty))
                {
                    result.Result = false;
                    result.Message = "填写数量大于检测的数量";
                    break;
                }
                if (checkDto.DefectQty < 0 || checkDto.ReworkQty < 0 || checkDto.LossQty < 0)
                {
                    result.Result = false;
                    result.Message = "填写数据有误，请重新填写";
                    break;
                }
                checkDto.WIPQty = int.Parse(item["WIPQTY"].ToString());//在制数
                checkDto.SpecimenLossQty = string.IsNullOrWhiteSpace(item["SPECIMENLOSSQTY"].ToString()) ? 0 : int.Parse(item["SPECIMENLOSSQTY"].ToString());//需开废票试件数
                checkDto.AcceptanceQty = checkDto.CheckQty - checkDto.LossQty - checkDto.SpecimenLossQty;//合格数量
                checkDto.AcceptanceQty2 = checkDto.AcceptanceQty - checkDto.DefectQty - checkDto.ReworkQty;
                checkDto.ContainerID = item["ContainerID"].ToString();//批次ID
                checkDto.ContainerName = item["ContainerName"].ToString();//批次名
                checkDto.WorkflowstepID = dtContainer.Rows[0]["WorkflowstepID"].ToString();//工序ID
                checkDto.StepInfoID = dtContainer.Rows[0]["StepInfoID"].ToString();//工步ID
                checkDto.ContainerStepWorkReportID = item["ContainerStepWorkReportID"].ToString();//报工ID
                checkDto.FactoryID = m_UserInfo.FactoryID;//工厂ID
                checkDto.CheckerID = m_UserInfo.EmployeeID.ToString();//检验员
                checkDto.CheckNote = item["CHECKNOTES"].ToString();//检验备注
                checkDto.FirstCheckContainerNo = item["FirstCheckContainerNo"].ToString();//首检批次号
                checkDto.FirstCheckBillNo = GetFirstCheckBillNo();

                checkDto.ReportType = int.Parse(item["CheckType"].ToString());//报工类型
                //if (checkDto.ReportType == 4)//返件报工
                //{
                //    repairContianer.Add(item["ContainerID"].ToString());
                //}
                //if (checkDto.ReportType == 3)//试件报工
                //{
                //    testContianer.Add(item["ContainerID"].ToString());
                //}
                StepWorkReportIDList += checkDto.ContainerStepWorkReportID + ",";
                checkList.Add(checkDto);
                if (checkDto.LossQty > 0)
                {
                    Dictionary<string, string> changeDic = new Dictionary<string, string>();
                    changeDic.Add("containerCheckInfoID", checkDto.ContainerCheckInfoID);//检验ID
                    changeDic.Add("containerID", item["ContainerID"].ToString());//批次ID
                    changeDic.Add("changeQtyType", "2");//数量变更类型（2为报废）
                    changeDic.Add("qty", (-checkDto.LossQty).ToString());//变更数量
                    changeDic.Add("reasonID", item["LOSSREASON"].ToString());
                    changeDic.Add("scrapSourceType", "1");//数据来源类型(1为工序检验)
                    changeDic.Add("containerStepWorkReportID", item["ContainerStepWorkReportID"].ToString());//报工ID
                    changeDic.Add("EmployeeID", m_UserInfo.EmployeeID.ToString());//记录人
                    changeDic.Add("WorkflowstepID", item["WorkflowstepID"].ToString());//工序ID
                    changeDic.Add("StepInfoID", dtContainer.Rows[0]["StepInfoID"].ToString());//工步ID
                    changeQtyPara.Add(changeDic);
                }
            }
        }
        //验证是否已存在检验（此情况针对在两台终端机同时登录同时检）
        if (result.Result && !string.IsNullOrWhiteSpace(StepWorkReportIDList))
        {
            StepWorkReportIDList = StepWorkReportIDList.Trim(',');
            DataTable dtCheck1 = checkBusiness.ContainerCheck2ValidateList(StepWorkReportIDList, 0);
            if (dtCheck1.Rows.Count > 0)
            {
                result.Result = false;
                result.Message = "此工步已有检验记录，请刷新页面";
            }
            if (!checkBusiness.IsVaildWorkReportForStepInfoCheck(StepWorkReportIDList, 0))
            {
                result.Result = false;
                result.Message = "此工步已撤销，请刷新页面";
            }
        }
        if (result.Result)
        {
            //保存检验记录
            result = checkBusiness.SaveStepInfoCheckInfo(checkList, paras);
            //插入批次报废变更记录
            if (result.Result && changeQtyPara.Count > 0)
            {
                foreach (Dictionary<string, string> dic in changeQtyPara)
                {
                    m_ContainerObj.AddCheckQtyChangeRecord(dic);
                }
            }
            //如果是子批次，更新子批次报废情况
            if (result.Result && containerType == "3")
            {
                ChangeChildContainerQty(dtCheck);
            }
            //检验结束，移动工序
            if (result.Result)
            {
                DataTable dtReCheck = dtCheck.DefaultView.ToTable(true, new string[8] { "ContainerID", "ContainerName", "WorkflowStepId", "StepInfoId", "workflowId", "sequence", "factoryId", "CheckType" });
                foreach (DataRow item in dtReCheck.Rows)
                {
                    DataTable containerQty = checkBusiness.GetAllAccepQtyListByStepInfo(item["ContainerID"].ToString());
                    int wipQty = 0, accepttanceQty = 0, lossQty = 0, defectqty = 0, reworkqty = 0;//在制数，合格数（不能用工序合格数），报废数
                    if (!string.IsNullOrWhiteSpace(containerQty.Rows[0]["QTY"].ToString()))
                    {
                        wipQty = int.Parse(containerQty.Rows[0]["QTY"].ToString());
                    }
                    //if (!string.IsNullOrWhiteSpace(containerQty.Rows[0]["ACCEPTANCEQTY"].ToString()))
                    //{
                    //    accepttanceQty = int.Parse(containerQty.Compute("SUM(ACCEPTANCEQTY)", string.Empty).ToString());
                    //}

                    //检查总表stepcheckNum,firstCheckNum
                    //string strUpdateinfo = "";
                    //strUpdateinfo = m_ConCurrentinfo.UpdateContainerCurrentinfoCheckInfo2(item["ContainerID"].ToString(), item["WorkflowStepID"].ToString());
                    BusinessRule.Common.LogHelp.WriteOrcale("检验日志记录" + "@^" + "批次：" + item["ContainerID"].ToString() + "@^" + "工序：" + item["WorkflowStepID"].ToString() + "工步：" + item["StepInfoId"].ToString() + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_UserInfo.FullName); //写入数据库   

                    if (item["CheckType"].ToString() == "1" && wipQty != 1)//首件且在制数不等于1
                    {
                        continue;
                    }
                    DataTable dtaccqty = checkBusiness.GetStepInfoAccepQty(item);//查询工序下的所有工步检验数
                    lossQty = int.Parse(dtaccqty.Compute("SUM(LOSSQTY)", string.Empty).ToString());//工序下所有工步报废数总和
                    defectqty = int.Parse(dtaccqty.Compute("SUM(defectqty)", string.Empty).ToString());//工序下所有工步超差数总和
                    reworkqty = int.Parse(dtaccqty.Compute("SUM(reworkqty)", string.Empty).ToString());//工序下所有工步返修数总和
                    if (lossQty > 0)
                    {
                        Dictionary<string, string> updatePara = new Dictionary<string, string>();
                        Dictionary<string, string> conditionPara = new Dictionary<string, string>();
                        conditionPara["ContainerID"] = String.Format("'{0}'", item["ContainerID"].ToString());
                        updatePara["alllossqty"] = lossQty.ToString();
                        m_ConCurrentinfo.UpdateContainerCurrentInfoByField(updatePara, conditionPara);
                    }
                    DataRow[] drs = dtaccqty.Select("stepinfoid = '" + item["StepInfoId"] + "'");//当前的工步
                    int currLossQty = int.Parse(drs[0]["LOSSQTY"].ToString());//当前工步的报废数
                    //如果检验工步存在检验完成，并且有报废数，则更改批次在制数，以及其余未完工工步的数据
                    if (currLossQty > 0 && int.Parse(drs[0]["checkqty"].ToString()) >= wipQty)
                    {
                        DataRow[] drs1 = dtaccqty.Select("stepinfoid <> '" + item["StepInfoId"] + "'");
                        SetContainerWipQty(drs1, wipQty, item, currLossQty);
                    }
                    DataRow[] dacs = dtaccqty.Select("checkqty<'" + wipQty + "'");
                    //只要有工步的检验数小于在制数且当前工步报废小于在制数，则不移动和添加工序记录
                    if (dacs.Length > 0 && currLossQty < wipQty)
                    {
                        continue;
                    }
                    accepttanceQty = int.Parse(drs[0]["Acceptanceqty"].ToString());//该工步的合格数
                    FillStepCheckInfo(item, accepttanceQty, lossQty, defectqty, reworkqty);//所有工步干完，填充工序检验信息
                    //if (accepttanceQty > (wipQty * dtaccqty.Rows.Count) && containerType == "2")//如果合格数大于在制数，且是数量批
                    //{
                    //    //添加超报的数量调整记录
                    //    DataTable dt = dtCheck.Select(string.Format("ContainerID = '{0}'", item["ContainerID"].ToString())).CopyToDataTable();
                    //    dt.DefaultView.Sort = "CREATEDATE desc";
                    //    string Max_date_workReportID = dt.Rows[0]["ContainerStepWorkReportID"].ToString();
                    //    ContainerCheckInfoDTO dto = checkList.Find(p => p.ContainerStepWorkReportID.Equals(Max_date_workReportID));
                    //    CheckQtyChangeAdd(dto, accepttanceQty - wipQty);
                    //}
                    Dictionary<String, String> dic = new Dictionary<String, String>() {{"ContainerID", item["ContainerID"].ToString()},
                                                                                       {"WorkflowStepID", item["WorkFlowStepID"].ToString()},
                                                                                       {"WorkflowID", item["WorkflowID"].ToString()},
                                                                                       {"Sequence", item["Sequence"].ToString()},
                                                                                       {"ContainerName", item["ContainerName"].ToString()}};
                    if (currLossQty >= wipQty)//如果全部报废完，则不移动
                    {
                        checkBusiness.MainContainerAutoWork(dic, m_UserInfo, true);//提前让主卡自动报工
                        continue;
                    }
                    string msg = "";
                    result.Result = checkBusiness.MoveNextStep(dic, host, accepttanceQty, levelAttributes, m_UserInfo, ref msg);
                    if (!result.Result)
                    {
                        result.Message = "工序移动失败：" + msg;
                        break;
                    }
                    //if (!MoveNextStep(item, ref msg, accepttanceQty))
                    //{
                    //    result.Result = false;
                    //    result.Message = "工序移动失败：" + msg;
                    //    break;
                    //}
                }
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 设置批次在制数，并退回未检验的工步
    /// </summary>
    /// <param name="drs">除了检验的工步外的其他工步</param>
    /// <param name="wipQty">在制数</param>
    /// <param name="dr">当前工步</param>
    /// <param name="lossQty">当前工步报废数</param>
    private void SetContainerWipQty(DataRow[] drs, int wipQty, DataRow dr, int lossQty)
    {
        System.Collections.ArrayList list = new System.Collections.ArrayList();
        for (int i = 0; i < drs.Length; i++)
        {
            if (int.Parse(drs[i]["checkqty"].ToString()) >= wipQty)//检验完的工步跳过
            {
                continue;
            }
            string sql = @"SELECT csw.containerstepworkreportid FROM containerstepworkreport2 csw 
LEFT JOIN containercheckinfo2 cci ON cci.containerstepworkreportid = csw.containerstepworkreportid AND cci.isuse = 0
WHERE csw.containerid = '{0}' AND csw.workflowstepid = '{1}' AND csw.stepinfoid = '{2}' AND csw.isuse = 0 AND cci.containercheckinfoid IS NULL";
            DataTable dt = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, dr["ContainerID"].ToString(), dr["WorkflowStepID"].ToString(), drs[i]["StepInfoID"].ToString()));
            foreach (DataRow item in dt.Rows)
            {
                //逻辑删除报工记录
                sql = @"UPDATE containerstepworkreport2 csww SET csww.isuse = 1 WHERE csww.containerstepworkreportid = '" + item["containerstepworkreportid"].ToString() + "'";
                list.Add(sql);
                //删除检测项
                sql = @"delete stepcheckpointresult sc WHERE sc.containerstepworkreportid='{0}' AND sc.containerid='{1}'
                    and sc.stepcheckpointid IN (select st.stepcheckpointid from stepcheckpoint st where st.workflowstepid='{2}' and st.stepinfoid='{3}') ";
                sql = string.Format(sql, item["containerstepworkreportid"].ToString(), dr["ContainerID"].ToString(), dr["WorkflowStepID"].ToString(), drs[i]["StepInfoID"].ToString());
                list.Add(sql);
            }
        }
        if (list.Count > 0 && lossQty < wipQty)
        {
            //撤销工序报工
            string strSql = "UPDATE containerstepworkreport c SET c.isuse = 1 WHERE c.containerid = '{0}' AND c.workflowstepid = '{1}' AND c.isuse = 0";
            strSql = String.Format(strSql, dr["ContainerID"].ToString(), dr["WorkflowStepID"].ToString());
            list.Add(strSql);
            DatabaseHelper.ExecuteSqlTran(list);
        }

        //更改批次数量
        m_ContainerObj.ChangeContainerQty(dr["ContainerID"].ToString(), -lossQty);
    }
    /// <summary>
    /// 更新子序号报废
    /// </summary>
    /// <param name="dtChild"></param>
    private void ChangeChildContainerQty(DataTable dtChild)
    {
        System.Collections.ArrayList list = new System.Collections.ArrayList();
        foreach (DataRow item in dtChild.Rows)
        {
            int LossQty = string.IsNullOrWhiteSpace(item["LOSSQTY"].ToString()) ? 0 : int.Parse(item["LOSSQTY"].ToString());//报废数
            if (LossQty > 0)
            {
                list.Add("UPDATE container c SET c.status = 2,c.qty=0 WHERE c.containerid = '" + item["childcontainerid"].ToString() + "'");
            }
        }
        if (list.Count > 0)
        {
            DatabaseHelper.ExecuteSqlTran(list);
        }
    }


    /// <summary>
    /// 填充工序检验信息
    /// </summary>
    /// <param name="container"></param>
    /// <param name="accepttanceQty"></param>
    /// <param name="lossQty"></param>
    /// <param name="defectqty"></param>
    /// <param name="reworkqty"></param>
    private void FillStepCheckInfo(DataRow container, int accepttanceQty, int lossQty, int defectqty, int reworkqty)
    {
        if (IsExistStepCheckInfo(container)) //如果存在工序检验，则不添加，避免重复数据
        {
            return;
        }
        List<object[]> SQLStringList = new List<object[]>();
        string sql = "SELECT cw.containerstepworkreportid FROM containerstepworkreport cw WHERE cw.containerid = '{0}' AND cw.workflowstepid = '{1}' and cw.isuse = 0";
        sql = string.Format(sql, container["ContainerID"].ToString(), container["WorkflowstepID"].ToString());
        DataTable dtStep = DatabaseHelper.Query_ReturnDatTable(sql);
        ContainerStepWorkReportDTO reportDto = new ContainerStepWorkReportDTO();
        if (dtStep.Rows.Count == 0) //如果不存在工序报工，则添加报工
        {
            sql = "SELECT cw.workerid FROM containerstepworkreport2 cw WHERE cw.containerid = '{0}' AND cw.workflowstepid = '{1}' and cw.isuse = 0 ORDER BY cw.createdate DESC";
            sql = string.Format(sql, container["ContainerID"].ToString(), container["WorkflowstepID"].ToString());
            DataTable dtStepInfo = DatabaseHelper.Query_ReturnDatTable(sql);//查询出最新一条工步报工的工人ID，赋值给工序报工工人
            reportDto.ContainerID = container["ContainerID"].ToString();
            reportDto.WorkflowstepID = container["WorkflowStepID"].ToString();
            reportDto.Qty = accepttanceQty + lossQty;
            reportDto.WorkerID = dtStepInfo.Rows.Count > 0 ? dtStepInfo.Rows[0]["workerid"].ToString() : m_UserInfo.EmployeeID.ToString();
            reportDto.FactoryID = m_UserInfo.FactoryID;
            reportDto.WorkCenterID = m_UserInfo.WorkCenterID;
            reportDto.ResourceID = "";
            reportDto.CheckerID = "";
            reportDto.FirstContainerNo = ""; //首件批次号
            reportDto.KeyProcessBatchNo = ""; //关键过程批次号
            reportDto.TeamID = m_UserInfo.TeamID;
            reportDto.CheckType = 2;
            reportDto.ContainerStepDispatchID = "";
            reportDto.ContainerStepWorkReportID = Guid.NewGuid().ToString();
            SQLStringList.Add(reportBusiness.FillContainerStepWorkReportInfoTrans(reportDto, ""));
        }
        ContainerCheckInfoDTO checkDto = new ContainerCheckInfoDTO();
        checkDto.DefectQty = defectqty; //超差数
        checkDto.ReworkQty = reworkqty; //返修数
        checkDto.LossQty = lossQty; //报废数
        checkDto.CheckQty = accepttanceQty + lossQty; //检验数量
        checkDto.WIPQty = accepttanceQty; //在制数
        checkDto.AcceptanceQty = accepttanceQty;
        checkDto.AcceptanceQty2 = accepttanceQty - defectqty - reworkqty;
        checkDto.ContainerName = container["ContainerName"].ToString();
        checkDto.ContainerID = container["ContainerID"].ToString();
        checkDto.WorkflowstepID = container["WorkflowstepID"].ToString();
        checkDto.FactoryID = m_UserInfo.FactoryID;
        checkDto.CheckerID = m_UserInfo.EmployeeID.ToString();
        checkDto.CheckNote = "";
        checkDto.ReportType = 2; //报工类型
        checkDto.ContainerStepWorkReportID = dtStep.Rows.Count > 0 ? dtStep.Rows[0]["ContainerStepWorkReportID"].ToString() : reportDto.ContainerStepWorkReportID;
        checkDto.FirstCheckContainerNo = "";
        checkDto.FirstCheckBillNo = GetFirstCheckBillNo();
        checkDto.SpecimenLossQty = 0; //需开废票试件数
        SQLStringList.Add(checkBusiness.FillContainerCheckInfo(checkDto));
        //更新工序的报废数
        sql = @"UPDATE CONTAINERSTEPWORKREPORT CSW SET CSW.LOSSQTY= '{0}',csw.qty='{1}'
                WHERE CSW.containerid = '{2}' AND CSW.workflowstepid = '{3}' AND CSW.isuse = 0";
        sql = String.Format(sql, lossQty, checkDto.CheckQty, container["ContainerID"].ToString(), container["WorkflowStepID"].ToString());
        if (dtStep.Rows.Count > 0)//如果存在报工记录，则同时更改报工报废数
        {
            SQLStringList.Add(new Object[] { sql });
            DatabaseHelper.ExecuteSqlTran(SQLStringList);
        }
        else
        {
            DatabaseHelper.ExecuteSqlTran(SQLStringList);
            DatabaseHelper.ExecuteSql(sql);
        }
    }

    /// <summary>
    /// 是否存在工序报工
    /// </summary>
    /// <param name="dr"></param>
    /// <returns></returns>
    public bool IsExistStepCheckInfo(DataRow dr)
    {
        string sql = "SELECT 1 FROM containercheckinfo cci WHERE cci.containerid = '{0}' AND cci.workflowstepid = '{1}' AND cci.isuse = 0";
        sql = string.Format(sql, dr["ContainerID"].ToString(), dr["WorkflowstepID"].ToString());
        if (DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(sql).Rows.Count == 0)
        {
            return false;
        }
        return true;
    }

    /// <summary>
    /// 获取首件检验单号，车间唯一
    /// </summary>
    /// <returns></returns>
    private string GetFirstCheckBillNo()
    {
        string strFactoryCode = commonBusiness.GetFatoryAttributes(m_UserInfo.FactoryID, "分厂代码");
        strFactoryCode = String.Format("{0}首-{1}", DateTime.Now.Year, strFactoryCode);
        strFactoryCode = checkBusiness.GetFirstCheckBillNo(strFactoryCode);
        return strFactoryCode;
    }

    /// <summary>
    /// 增加检验记录 --超报
    /// </summary>
    /// <param name="dto"></param>
    /// <param name="changeQty"></param>
    private void CheckQtyChangeAdd(ContainerCheckInfoDTO dto, int changeQty)
    {
        DataTable qtyadjustrea_dt = commonBusiness.GetQtyAdjustReason();
        string reasonID = "";
        foreach (DataRow item in qtyadjustrea_dt.Rows)
        {
            if (item["qtyadjustreasonname"].ToString() == "报工数量变更")
            {
                reasonID = item["qtyadjustreasonid"].ToString();
                break;
            }
        }
        AddQtyChangRecord(dto.ContainerCheckInfoID, dto.ContainerID, "1", changeQty.ToString(), reasonID, dto.ContainerStepWorkReportID, dto.WorkflowstepID);
        m_ContainerObj.ChangeContainerQty(dto.ContainerID, changeQty);
    }
    /// <summary>
    /// 添加批次数量改变记录
    /// </summary>
    /// <param name="checkInfoID"></param>
    /// <param name="containerID"></param>
    /// <param name="type"></param>
    /// <param name="qty"></param>
    /// <param name="ReasonID"></param>
    /// <param name="ContainerStepWorkReportID"></param>
    /// <param name="workflowStepID"></param>
    private void AddQtyChangRecord(string checkInfoID, string containerID, string type, string qty, string ReasonID, string ContainerStepWorkReportID, string workflowStepID)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("containerCheckInfoID", checkInfoID);
        para.Add("containerID", containerID);
        para.Add("changeQtyType", type);
        para.Add("qty", qty);
        para.Add("reasonID", ReasonID);
        para.Add("containerStepWorkReportID", ContainerStepWorkReportID);
        para.Add("scrapSourceType", "1"); //工序检验类型
        para.Add("EmployeeID", m_UserInfo.EmployeeID.ToString());
        para.Add("WorkflowstepID", workflowStepID);
        m_ContainerObj.AddCheckQtyChangeRecord(para);
    }


    /// <summary>
    /// 获取合卡批次的明细批次
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    private DataTable GetCombinateContainerDetail(DataTable dt)
    {
        string sql = @"SELECT cci.containerid,cci.containername,cci.containertype,cci.productid,cci.workflowid,s.stepno,s.stepinfoid,s.description stepinfoname,s.stepseq,cci.firstchecknum,cci.stepchecknum,
cci.workflowstepname,cci.workflowstepid,cci.factoryid,cci.qty AS wipqty,csr.qty,e.fullname employeename,csr.checktype,csr.containerstepworkreportid,csr.createdate,cci.workflowstepsequence AS SEQUENCE,'{2}' NOTES
FROM containercombinate cb
LEFT JOIN Containercurrentinfo cci ON cci.containerid = cb.containerid
LEFT JOIN containerstepworkreport2 csr ON csr.containerid = cci.containerid AND csr.workflowstepid = cci.workflowstepid
LEFT JOIN containercheckinfo2 cc ON cc.containerstepworkreportid = csr.containerstepworkreportid AND cc.isuse = 0
LEFT JOIN stepinfo s ON s.workflowstepid = csr.workflowstepid AND s.stepinfoid = csr.stepinfoid
LEFT JOIN employee e ON e.employeeid = csr.workerid
WHERE csr.isuse = 0 AND cc.containercheckinfoid IS NULL
AND cci.isinstore in (-1,0) AND cci.containerstatus=1 
AND cb.containercombinatename = '{0}' AND s.stepinfoid = '{1}'";
        string strSql = string.Empty;
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (i != 0)
            {
                strSql += @"
                            UNION ALL
                            ";
            }
            DataRow item = dt.Rows[i];
            strSql += string.Format(sql, item["containername"].ToString(), item["stepinfoid"].ToString(), item["notes"].ToString());
        }
        return DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(strSql);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}